package inline.core;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.Menu.Item;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class InlineBasketActivity extends ListActivity {
	// private static final String LOG_TAG = "InlineProductsActivity";

	private ProductsInBasketDbAdapter mDbHelper;
	private InlineService inlineService;
	public static final int SHOW_PRODUCTS_CODE = Menu.FIRST;
	private static final int EMPTY_BASKET = Menu.FIRST + 1;
	private static final int MAKE_ORDER = Menu.FIRST + 2;
	private TextView totalTextView ;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.basket_list);
	}

	@Override
	public void onResume() {
		super.onResume();
		inlineService = new InlineService(this);
		inlineService.open();
		mDbHelper = inlineService.getBasketDb();
		fillData();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		inlineService.close();
		stopManagingCursor(productsInBasketCursor);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, EMPTY_BASKET, "Esvaziar Carrinho");
		menu.add(1, MAKE_ORDER, "Enviar Pedido");
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, Item item) {
		switch (item.getId()) {

		case MAKE_ORDER:
			Toast.makeText(this, "Seu pedido foi enviado.", Toast.LENGTH_LONG).show();
		case EMPTY_BASKET:
			inlineService.clearBakset();
			fillData();
			return true;
		}
		

		return super.onMenuItemSelected(featureId, item);

	}

	private Cursor productsInBasketCursor;

	private void fillData() {
		totalTextView = (TextView) findViewById(R.id.basket_total);
		productsInBasketCursor = mDbHelper.fetchBasket();
		startManagingCursor(productsInBasketCursor);

		String[] from = new String[] { ProductsDbAdapter.KEY_NAME,
				ProductsInBasketDbAdapter.KEY_AMOUNT,
				ProductsDbAdapter.KEY_UNIT_PRICE };

		int[] to = new int[] { R.id.bakset_product_name, R.id.product_amount,
				R.id.bakset_product_unit_price };

		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter basket = new SimpleCursorAdapter(this,
				R.layout.basket_product_row, productsInBasketCursor, from, to);
		setListAdapter(basket);
		
		try {
			totalTextView.setText(""+mDbHelper.fetchBasketTotal());
		} catch (RuntimeException e) {
			totalTextView.setText("0.00");
		}
	}

}